package com.mycompany.app.common.mail;

import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.VelocityException;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.velocity.VelocityEngineUtils;

/**
 * Class for sending e-mail messages based on Velocity templates
 * or with attachments.
 * 
 * @author Matt Raible
 */
public class MailEngine {
    private final Log log = LogFactory.getLog(MailEngine.class);

    private MailSender mailSender;

    private VelocityEngine velocityEngine;

    public void setMailSender(MailSender mailSender) {

        this.mailSender = mailSender;
    }

    public void setVelocityEngine(VelocityEngine velocityEngine) {

        this.velocityEngine = velocityEngine;
    }

    /**
     * Send a simple message based on a Velocity template.
     * @param msg the message to populate
     * @param templateName the Velocity template to use (relative to classpath)
     * @param model a map containing key/value pairs
     */
    public void sendMessage(SimpleMailMessage msg, String templateName,
            Map model) {

        String result = null;

        try {
            result = VelocityEngineUtils.mergeTemplateIntoString(
                    velocityEngine, templateName, model);
        } catch (VelocityException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }

        msg.setText(result);
        send(msg);
    }

    /**
     * Send a simple message with pre-populated values.
     * @param msg the message to send
     */
    public void send(SimpleMailMessage msg) {

        try {
            mailSender.send(msg);
        } catch (MailException ex) {
            //log it and go on
            log.error(ex.getMessage());
        }
    }

    /**
     * Convenience method for sending messages with attachments.
     * 
     * @param recipients array of e-mail addresses
     * @param sender e-mail address of sender
     * @param resource attachment from classpath
     * @param bodyText text in e-mail
     * @param subject subject of e-mail
     * @param attachmentName name for attachment
     * @throws MessagingException thrown when can't communicate with SMTP server
     * @author Ben Gill
     */
    public void sendMessage(String[] recipients, String sender,
            ClassPathResource resource, String bodyText, String subject,
            String attachmentName) throws MessagingException {

        MimeMessage message = ((JavaMailSenderImpl) mailSender)
                .createMimeMessage();

        // use the true flag to indicate you need a multipart message
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        helper.setTo(recipients);
        helper.setFrom(sender);
        helper.setText(bodyText);
        helper.setSubject(subject);

        helper.addAttachment(attachmentName, resource);

        ((JavaMailSenderImpl) mailSender).send(message);
    }

    /**
     * Send Email with HTML Content with Velocity Template Support
     * and zip file attachment 
     * 
     * @param emailAddress
     * @param fromAddress
     * @param subject
     * @param isHtmlPart
     * @param templateName
     * @param resource
     * @param attachmentName
     * @param model
     * @throws MessagingException
     */
    public void sendMessage(String emailAddress, String fromAddress,
            String subject, boolean isHtmlPart, String templateName,
            FileSystemResource resource, String attachmentName, Map model)
            throws MessagingException {

        //Check input properties
        if (resource == null || StringUtils.isEmpty(templateName)) {
            log
                    .equals("Can not find a attachement file to send or template to use.");
            return;
        }

        MimeMessage message = ((JavaMailSenderImpl) mailSender)
                .createMimeMessage();

        // use the true flag to indicate you need a multipart message
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

        //Set Basic Properties
        helper.setTo(emailAddress);
        helper.setFrom(fromAddress);
        helper.setSubject(subject);

        // Attach zip file
        helper.addAttachment(attachmentName, resource);

        // Email Body Template
        String result = null;
        try {
            result = VelocityEngineUtils.mergeTemplateIntoString(
                    velocityEngine, templateName, model);
        } catch (VelocityException e) {
            e.printStackTrace();
        }
        helper.setText(result, isHtmlPart);
        //Sending
        ((JavaMailSenderImpl) mailSender).send(message);
    }
}
